import re
from html import escape
from webob import Response
from webob.dec import wsgify


class Application:
    def __init__(self):
        self.routes = []

    def route(self, rule, handler):
        self.routes.append((rule, handler))

    @wsgify
    def __call__(self, request):
        for rule, handler in self.routes:
            if re.match(rule, request.path):
                return handler(request)


def main(request):
    return Response('this is the main page')


def favicon(request):
    with open('./favicon.ico', 'rb') as f:
        return Response(body=f.read(), content_type='image/x-icon')


def hello(request):
    name = request.params.get('name', 'anon')
    body = 'hello {}'.format(escape(name))
    return Response(body)


if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    application = Application()

    application.route(r'/favicon$', favicon)
    application.route(r'/hello$', hello)
    application.route(r'/$', main)

    server = make_server('0.0.0.0', 3000, application)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
